// 获取DOM元素
const jobForm = document.getElementById('job-form');
const resultContent = document.getElementById('result-content');
const scoreElement = document.getElementById('score');
const analysisList = document.getElementById('analysis-list');
const hourlyRateElement = document.getElementById('hourly-rate');

// 添加页面加载动画
document.body.classList.add('loaded');

// 获取所有滑块和对应的值显示元素
const sliders = ['benefits', 'environment', 'pressure', 'growth', 'stability'];
sliders.forEach(slider => {
    const sliderElement = document.getElementById(slider);
    const valueElement = document.getElementById(`${slider}Value`);
    
    // 更新滑块颜色
    updateSliderColor(sliderElement);
    
    // 更新滑块值显示
    sliderElement.addEventListener('input', () => {
        valueElement.textContent = sliderElement.value;
        updateSliderColor(sliderElement);
    });
});

// 更新滑块颜色函数
function updateSliderColor(slider) {
    const min = slider.min ? parseFloat(slider.min) : 0;
    const max = slider.max ? parseFloat(slider.max) : 10;
    const value = parseFloat(slider.value);
    const percentage = ((value - min) / (max - min)) * 100;
    
    // 根据不同的滑块ID设置不同的渐变色
    let gradientColor;
    
    if (slider.id === 'pressure') {
        // 这些是负面因素，红色到绿色
        gradientColor = `linear-gradient(to right, #2ecc71 0%, #2ecc71 ${100-percentage}%, #e0e0e0 ${100-percentage}%, #e0e0e0 100%)`;
    } else {
        // 正面因素，绿色到蓝色
        gradientColor = `linear-gradient(to right, #e0e0e0 0%, #e0e0e0 ${percentage}%, #3498db ${percentage}%, #3498db 100%)`;
    }
    
    slider.style.background = gradientColor;
}

// 表单提交处理
jobForm.addEventListener('submit', function(e) {
    e.preventDefault();
    
    // 添加按钮加载动画
    const submitButton = document.querySelector('button[type="submit"]');
    submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 计算中...';
    submitButton.disabled = true;
    
    // 延迟执行以显示加载效果
    setTimeout(() => {
        // 收集表单数据
        const formData = {
            salary: parseFloat(document.getElementById('salary').value),
            workHours: parseFloat(document.getElementById('workHours').value),
            commuteTime: parseFloat(document.getElementById('commuteTime').value),
            education: parseInt(document.getElementById('education').value),
            experience: parseFloat(document.getElementById('experience').value),
            overtime: parseFloat(document.getElementById('overtime').value),
            benefits: parseInt(document.getElementById('benefits').value),
            environment: parseInt(document.getElementById('environment').value),
            pressure: parseInt(document.getElementById('pressure').value),
            growth: parseInt(document.getElementById('growth').value),
            stability: parseInt(document.getElementById('stability').value)
        };
        
        // 计算性价比
        const result = calculateJobValue(formData);
        
        // 显示结果
        displayResult(result);
        
        // 恢复按钮状态
        submitButton.innerHTML = '计算性价比';
        submitButton.disabled = false;
    }, 800); // 800ms的延迟，给用户一个计算的感觉
});

// 计算工作性价比
function calculateJobValue(data) {
    // 计算每月实际工作时间（包括通勤和加班）
    const commuteDaysPerMonth = 22; // 假设每月工作22天
    const commuteHoursPerMonth = (data.commuteTime * 2 / 60) * commuteDaysPerMonth; // 每月通勤时间（小时）
    const regularHoursPerMonth = (data.workHours / 5) * commuteDaysPerMonth; // 每月常规工作时间
    const totalWorkHours = regularHoursPerMonth + commuteHoursPerMonth + data.overtime;
    
    // 计算实际时薪
    const hourlyRate = data.salary / totalWorkHours;
    
    // 计算各项指标得分
    const scores = {};
    
    // 1. 薪资得分 (0-30分)
    // 基于时薪计算，假设100元/小时为满分
    scores.salary = Math.min(30, (hourlyRate / 100) * 30);
    
    // 2. 工作时间得分 (0-15分)
    // 工作时间越少，得分越高，假设每周40小时为标准
    const workHoursScore = Math.max(0, 15 - ((data.workHours - 40) * 0.5));
    scores.workHours = workHoursScore;
    
    // 3. 通勤时间得分 (0-10分)
    // 通勤时间越短，得分越高
    scores.commuteTime = Math.max(0, 10 - (data.commuteTime / 15));
    
    // 4. 学历要求与个人匹配度 (0-5分)
    // 假设学历要求越低，对工作者负担越小，得分越高
    scores.education = Math.max(0, 6 - data.education);
    
    // 5. 工作经验要求 (0-5分)
    // 经验要求越低，对工作者负担越小，得分越高
    scores.experience = Math.max(0, 5 - data.experience * 0.5);
    
    // 6. 加班情况 (0-10分)
    // 加班越少，得分越高
    scores.overtime = Math.max(0, 10 - (data.overtime / 10));
    
    // 7. 福利待遇 (0-5分)
    scores.benefits = data.benefits * 0.5;
    
    // 8. 工作环境 (0-5分)
    scores.environment = data.environment * 0.5;
    
    // 9. 工作压力 (0-10分)
    // 压力越小，得分越高
    scores.pressure = Math.max(0, 10 - data.pressure);
    
    // 10. 成长空间 (0-5分)
    scores.growth = data.growth * 0.5;
    
    // 11. 工作稳定性 (0-5分)
    scores.stability = data.stability * 0.5;
    
    // 添加因素的描述和图标
    const factorDescriptions = {
        salary: { name: '薪资水平', icon: 'fa-money-bill-wave', positive: true },
        workHours: { name: '工作时长', icon: 'fa-clock', positive: false },
        commuteTime: { name: '通勤时间', icon: 'fa-car', positive: false },
        education: { name: '学历要求', icon: 'fa-graduation-cap', positive: false },
        experience: { name: '经验要求', icon: 'fa-briefcase', positive: false },
        overtime: { name: '加班情况', icon: 'fa-business-time', positive: false },
        benefits: { name: '福利待遇', icon: 'fa-gift', positive: true },
        environment: { name: '工作环境', icon: 'fa-building', positive: true },
        pressure: { name: '工作压力', icon: 'fa-weight-hanging', positive: false },
        growth: { name: '成长空间', icon: 'fa-chart-line', positive: true },
        stability: { name: '工作稳定性', icon: 'fa-shield-alt', positive: true }
    };
    
    // 计算总分 (满分100分)
    let totalScore = 0;
    for (const key in scores) {
        totalScore += scores[key];
    }
    
    // 四舍五入到整数
    totalScore = Math.round(totalScore);
    
    // 返回结果
    return {
        totalScore,
        scores,
        hourlyRate: hourlyRate.toFixed(2),
        totalWorkHours: totalWorkHours.toFixed(1),
        factorDescriptions
    };
}

// 显示计算结果
function displayResult(result) {
    // 显示总分（使用计数器动画）
    const targetScore = result.totalScore;
    let currentScore = 0;
    const duration = 1500; // 1.5秒完成计数
    const interval = 20; // 每20毫秒更新一次
    const increment = targetScore / (duration / interval);
    
    const counter = setInterval(() => {
        currentScore += increment;
        if (currentScore >= targetScore) {
            clearInterval(counter);
            currentScore = targetScore;
        }
        scoreElement.textContent = Math.round(currentScore);
    }, interval);
    
    // 显示实际时薪（使用计数器动画）
    const targetRate = parseFloat(result.hourlyRate);
    let currentRate = 0;
    const rateIncrement = targetRate / (duration / interval);
    
    const rateCounter = setInterval(() => {
        currentRate += rateIncrement;
        if (currentRate >= targetRate) {
            clearInterval(rateCounter);
            currentRate = targetRate;
        }
        hourlyRateElement.textContent = currentRate.toFixed(2);
    }, interval);
    
    // 清空分析列表
    analysisList.innerHTML = '';
    
    // 添加分析项目
    const analysisItems = [
        { name: '薪资水平', score: result.scores.salary, max: 30, description: `实际时薪 ${result.hourlyRate} 元/小时` },
        { name: '工作时长', score: result.scores.workHours, max: 15, description: '每周工作时间与标准工时(40小时)的比较' },
        { name: '通勤时间', score: result.scores.commuteTime, max: 10, description: '单程通勤时间的合理性' },
        { name: '学历要求', score: result.scores.education, max: 5, description: '学历要求的合理性' },
        { name: '经验要求', score: result.scores.experience, max: 5, description: '工作经验要求的合理性' },
        { name: '加班情况', score: result.scores.overtime, max: 10, description: '每月加班时长的合理性' },
        { name: '福利待遇', score: result.scores.benefits, max: 5, description: '公司提供的福利水平' },
        { name: '工作环境', score: result.scores.environment, max: 5, description: '工作环境的舒适度' },
        { name: '工作压力', score: result.scores.pressure, max: 10, description: '工作压力的合理性' },
        { name: '成长空间', score: result.scores.growth, max: 5, description: '职业发展和技能提升的机会' },
        { name: '工作稳定性', score: result.scores.stability, max: 5, description: '工作的长期稳定性' }
    ];
    
    // 按得分比例从高到低排序
    analysisItems.sort((a, b) => (b.score / b.max) - (a.score / a.max));
    
    // 延迟添加每个因素的分析，创建动画效果
    analysisItems.forEach((item, index) => {
        setTimeout(() => {
            const percentage = Math.round((item.score / item.max) * 100);
            const li = document.createElement('li');
            
            // 获取对应的图标
            const factor = Object.keys(result.scores).find(key => 
                result.factorDescriptions[key].name === item.name
            );
            const icon = factor ? result.factorDescriptions[factor].icon : 'fa-check';
            
            // 设置样式和内容
            li.style.opacity = '0';
            li.style.transform = 'translateX(20px)';
            li.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            
            // 根据得分比例添加颜色和背景
            let color, bgColor;
            if (percentage >= 80) {
                color = '#27ae60'; // 绿色，很好
                bgColor = 'rgba(46, 204, 113, 0.1)';
            } else if (percentage >= 60) {
                color = '#2980b9'; // 蓝色，良好
                bgColor = 'rgba(52, 152, 219, 0.1)';
            } else if (percentage >= 40) {
                color = '#f39c12'; // 橙色，一般
                bgColor = 'rgba(243, 156, 18, 0.1)';
            } else {
                color = '#e74c3c'; // 红色，较差
                bgColor = 'rgba(231, 76, 60, 0.1)';
            }
            
            li.style.backgroundColor = bgColor;
            li.style.borderLeft = `4px solid ${color}`;
            li.style.padding = '10px';
            li.style.marginBottom = '8px';
            li.style.borderRadius = '4px';
            
            li.innerHTML = `
                <i class="fas ${icon}" style="color: ${color}; margin-right: 8px;"></i>
                <strong>${item.name}</strong>: ${item.score}/${item.max}分 (${percentage}%) - ${item.description}
                <div class="progress-bar" style="background: linear-gradient(to right, ${color} ${percentage}%, #e0e0e0 ${percentage}%); width: 100%; height: 4px; margin-top: 5px; border-radius: 2px;"></div>
            `;
            
            analysisList.appendChild(li);
            
            // 触发动画
            setTimeout(() => {
                li.style.opacity = '1';
                li.style.transform = 'translateX(0)';
            }, 50);
        }, index * 100); // 每个因素延迟100ms添加
    });
    
    // 显示结果区域
    resultContent.classList.remove('hidden');
    
    // 平滑滚动到结果区域
    document.getElementById('result').scrollIntoView({ behavior: 'smooth' });
}

// 添加工作性价比评级解释
function getScoreRating(score) {
    if (score >= 90) return '极佳';
    if (score >= 80) return '优秀';
    if (score >= 70) return '良好';
    if (score >= 60) return '一般';
    if (score >= 50) return '较差';
    return '不推荐';
}

// 添加重置按钮功能
const resetButton = document.createElement('button');
resetButton.type = 'button';
resetButton.className = 'reset-btn';
resetButton.innerHTML = '<i class="fas fa-redo"></i> 重置表单';
resetButton.style.marginTop = '20px';
resetButton.style.backgroundColor = '#7f8c8d';
resetButton.style.color = 'white';
resetButton.style.border = 'none';
resetButton.style.borderRadius = '10px';
resetButton.style.padding = '12px';
resetButton.style.width = '100%';
resetButton.style.cursor = 'pointer';
resetButton.style.fontWeight = '600';
resetButton.style.transition = 'all 0.3s';

resetButton.addEventListener('mouseover', function() {
    this.style.backgroundColor = '#95a5a6';
    this.style.transform = 'translateY(-2px)';
});

resetButton.addEventListener('mouseout', function() {
    this.style.backgroundColor = '#7f8c8d';
    this.style.transform = 'translateY(0)';
});

resetButton.addEventListener('click', function() {
    jobForm.reset();
    resultContent.classList.add('hidden');
    
    // 重置所有滑块的颜色和值显示
    sliders.forEach(slider => {
        const sliderElement = document.getElementById(slider);
        const valueElement = document.getElementById(`${slider}Value`);
        valueElement.textContent = sliderElement.value;
        updateSliderColor(sliderElement);
    });
});

// 将重置按钮添加到表单底部
jobForm.appendChild(resetButton);

// 添加页面加载动画CSS
document.head.insertAdjacentHTML('beforeend', `
<style>
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

body.loaded .calculator,
body.loaded .result,
body.loaded header h1,
body.loaded header p {
    animation: fadeInUp 0.8s ease-out forwards;
}

body.loaded header h1 {
    animation-delay: 0.1s;
}

body.loaded header p {
    animation-delay: 0.2s;
}

body.loaded .calculator {
    animation-delay: 0.3s;
}

body.loaded .result {
    animation-delay: 0.4s;
}

.reset-btn:active {
    transform: translateY(1px) !important;
}
</style>
`);